<template>
  <scroll-view scroll-y enable-back-to-top>
    <view style="background: #fff">
      <basics-form
        ref="basicsForm"
        @submit="submit"
        @selectCallback="selectCallback"
        :slotData="{ codeWaitTime }"
        :hiddenMustIcon="hiddenMustIcon"
        @pictureCallback="pictureCallback"
      >
        <template v-slot:inside="{ ruleKey, slotData }">
          <text
            style="margin-left: 40rpx"
            v-if="ruleKey == 'smsCode'"
            @click="getCode"
            :class="['my-active', slotData.codeWaitTime != 60 ? 'my-disabled' : '', 'login-code']"
          >
            {{ slotData.codeWaitTime == 60 ? "获取验证码" : slotData.codeWaitTime + "s后重试" }}
          </text>
        </template>
      </basics-form>
    </view>
    <view style="height: 600rpx" />
    <foot-button
      v-if="showButton"
      style="position: fixed; bottom: 0rpx; z-index: 10"
      :buttonList="buttonList"
      @tapButton="tapButton"
    />
  </scroll-view>
</template>

<script>
import basicsForm from "@/components/basics-form/basics-form.vue";
import footButton from "@/components/foot-button/foot-button.vue";
import form from "@/common/tui-validation.js";

export default {
  components: {
    basicsForm,
    footButton,
  },
  data() {
    return {
      patientId: uni.getStorageSync("patientId"),
      nationList: uni.getStorageSync("nationList"),
      patientData: null,
      diseaseList: [],
      buttonList: [
        {
          name: `重置`,
          icon: "zhongzhi-",
        },
        {
          name: `保存`,
          icon: "save",
        },
      ],
      height: 0,
      weight: 0,
      hiddenMustIcon: false,
      showButton: true,
      addFlag: true,
      codeWaitTime: 60,
      timer: null,
      token: uni.getStorageSync("token"),
      telphone: "",
    };
  },
  created(options) {},
  methods: {
    //获取患者信息,传入patientId代表医生看患者，不传代表患者自己看
    getPatient(patientId) {
    //   if (!patientId) {
    //     this.addFlag = false;
    //     // this.hiddenMustIcon = true;
    //     // this.showButton = false;
    //   }
	  this.addFlag = false;
      this.$api.doctorPatientDetail({ patientId: patientId || this.patientId }).then((res) => {
        if (res.code == 200) {
		  this.patientId= res.data.patientId
          this.height = res.data.height || 0;
          this.weight = res.data.weight || 0;
          res.data.birthday?res.data.age = this.$util.getAgeBirth(res.data.birthday):''
          if (this.height && this.weight) {
            res.data.bmi = Number((Number(this.weight) / Number(this.height) / Number(this.height)) * 10000).toFixed(2);
          } else {
            res.data.bmi = "";
          }
          this.patientData = res.data;
		  if (this.nationList) {
		    this.doctorListDiseaseCategory(res.data, false);
		  } else {
		    this.doctorListNation(res.data, false);
		  }
          // if (patientId) {
          //   if (this.nationList) {
          //     this.doctorListDiseaseCategory(res.data, false);
          //   } else {
          //     this.doctorListNation(res.data, false);
          //   }
          // } else {
          //   this.initRules(res.data, true);
          // }
        }
      });
    },
    //民族
    doctorListNation(data, disabled) {
      this.$api.doctorListNation().then((res) => {
        if (res.code == 200) {
          this.nationList = res.data;
          uni.setStorageSync("nationList", res.data);
          this.doctorListDiseaseCategory(data, disabled);
        }
      });
    },
    //病类
    doctorListDiseaseCategory(data, disabled) {
      this.$api.doctorListDiseaseCategory().then((res) => {
        if (res.code == 200) {
          this.diseaseList = res.data;
          this.initRules(data, disabled);
        }
      });
    },
    initRules(data, disabled) {
      let rules = [
        {
          title: "身份证照片",
          key: "idCardImg",
          type: "img",
          callback: true,
          disabled,
          tips: disabled ? "" : "上传后自动识别以下部分信息",
          hidden: disabled,
          skip: true,
        },
        {
          title: "患者姓名",
          key: "name",
          value: data.name || "",
          ruleList: ["minLength:2"],
          ruleMsgList: ["患者姓名至少2位"],
          disabled,
        },
        {
          title: "手机号",
          key: "telphone",
          value: data.telphone || "",
          type: "number",
          maxlength: 11,
          ruleList: ["isMobile"],
          ruleMsgList: ["请输入正确的手机号码"],
          callback: true,
          disabled,
        },
        {
          title: "验证码",
          key: "smsCode",
          type: "number",
          maxlength: 6,
          hidden: this.patientData || !this.addFlag,
          contentWidth: "20vw",
          tips: this.patientData ? "修改患者手机号需输入验证码" : "",
        },
        {
          title: "身份证号",
          key: "idCard",
          value: data.idCard || "",
          ruleList: ["isIdCard"],
          ruleMsgList: ["请输入正确的身份证号"],
          disabled,
		  callback:true
        },
        {
          title: "性别",
          key: "sex",
          value: disabled ? (data.sex ? "男" : "女") : 1 - data.sex,
          type: disabled ? "" : "radio",
          selectList: [
            {
              name: "男",
              value: 1,
            },
            {
              name: "女",
              value: 0,
            },
          ],
          selectKey: "value",
          disabled,
        },
        {
          title: "出生日期",
          key: "birthday",
          value: data.birthday || "",
          type: disabled ? "" : "selectDate",
          disabled,
          callback: true,
        },
        {
          title: "年龄",
          key: "age",
          value: data.age !== "" && data.age !== null && data.age !== undefined ? data.age : "",
          disabled: true,
          tips: disabled ? "" : "自动计算，不可编辑",
        },
        {
          title: "民族",
          key: "nation",
          value: disabled ? data.nation : data.nation ? this.nationList.indexOf(data.nation) : "",
          type: disabled ? "" : "select",
          selectList: this.nationList,
          disabled,
        },
        {
          title: "城市",
          key: "pca",
          addressDetailsKey: "address",
          value: disabled
            ? (data.provinceName || "") + (data.cityName || "") + (data.areaName || "")
            : data.provinceName
            ? [data.provinceName || "", data.cityName || "", data.areaName || ""]
            : "",
          type: disabled ? "" : "address",
          disabled,
        },
        {
          title: "详细地址",
          key: "address",
          value: data.address || "",
          type: "textarea",
          disabled,
        },
        {
          title: "身高(cm)",
          key: "height",
          value: Number(data.height) || "",
          disabled,
          ruleList: ["isAmount", "numMin:10"],
          ruleMsgList: ["身高必须是数字最多两位小数", "身高最小为10"],
          callback: true,
          skip: true,
        },
        {
          title: "体重(kg)",
          key: "weight",
          value: Number(data.weight) || "",
          disabled,
          ruleList: ["isAmount", "numMin:10"],
          ruleMsgList: ["体重必须是数字最多两位小数", "体重最小为10"],
          callback: true,
          skip: true,
        },
        {
          title: "BMI",
          key: "bmi",
          value: Number(data.bmi) || "",
          disabled: true,
          tips: disabled ? "" : "自动计算，不可编辑",
          skip: true,
        },
        {
          title: "腰围(cm)",
          key: "waist",
          value: Number(data.waist) || "",
          disabled,
          ruleList: ["isAmount", "numMin:10"],
          ruleMsgList: ["腰围必须是数字最多两位小数", "腰围最小为10"],
          skip: true,
        },
        {
          title: "臀围(cm)",
          key: "hipline",
          value: Number(data.hipline) || "",
          disabled,
          ruleList: ["isAmount", "numMin:10"],
          ruleMsgList: ["臀围必须是数字最多两位小数", "臀围最小为10"],
          skip: true,
        },
        {
          title: "病类",
          key: "diseaseCategory",
          value: disabled
            ? data.diseaseCategory
            : data.diseaseCategory
            ? this.diseaseList.indexOf(data.diseaseCategory)
            : "",
          type: disabled ? "" : "select",
          selectList: this.diseaseList,
          disabled,
          maxSelectCount: 1,
        },
        {
          title: "确诊日期",
          key: "diagnosisDate",
          value: data.diagnosisDate || "",
          type: disabled ? "" : "selectDate",
          disabled,
          skip: true,
        },
		{
		  title: "有无血压报告",
		  key: "isHaveDynamicReport",
		  value: disabled ? (data.isHaveDynamicReport ? "有" : "无") : 1 - data.isHaveDynamicReport,
		  type: disabled ? "" : "radio",
		  selectList: [
		    {
		      name: "有",
		      value: 1,
		    },
		    {
		      name: "无",
		      value: 0,
		    },
		  ],
		  selectKey: "value",
		  disabled,
		},
      ];
      this.$nextTick(() => {
        console.log(this.$refs.basicsForm);
        this.$refs.basicsForm.initForm(rules);
      });
    },
    //图片更换回调
    pictureCallback(param) {
      console.log(param, "---");
      if (param.url) {
        uni.showLoading({
          mask: true,
          title: "上传识别中",
        });
        uni.uploadFile({
          url: this.$api.baseUrl + this.$api.urlPrefix + "doctor/discernIdCard",
          filePath: param.url,
          name: "file",
          header: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + this.token,
          },
          success: (res) => {
            uni.hideLoading();
            let data = JSON.parse(res.data);
            if (data.code == 200) {
              this.$util.showSuccessToast("识别成功");
              this.changeParamValue(data.data);
            } else if (data.code == 401) {
              this.util.cleanLoginInfo();
            } else {
              this.$util.showToast("识别失败，请测试重新拍摄上传");
              this.$refs.basicsForm.changeParamValue({
                key: "idCardImg",
                value: "",
              });
            }
          },
          fail: (res) => {
            uni.hideLoading();
            this.$util.showToast("上传失败");
          },
        });
      }
    },
    changeParamValue(data) {
      console.log(data);
      this.$refs.basicsForm.changeParamValue({
        key: "idCardImg",
        value: data.idCardImg,
      });
      this.$refs.basicsForm.changeParamValue({
        key: "name",
        value: data.name,
      });
      this.$refs.basicsForm.changeParamValue({
        key: "idCard",
        value: data.idCard,
      });
      this.$refs.basicsForm.changeParamValue({
        key: "age",
        value: data.age,
      });
      this.$refs.basicsForm.changeParamValue({
        key: "birthday",
        value: data.birthday,
      });
      this.$refs.basicsForm.changeParamValue({
        key: "nation",
        value: this.nationList.indexOf(data.nation),
      });
      this.$refs.basicsForm.changeParamValue({
        key: "sex",
        value: 1 - data.sex,
      });
    },
    selectCallback(data) {
		if (data.key == "telphone") {
			this.telphone = data.value;
			if (this.patientData) {
			  if (data.value != this.patientData.telphone) {
				this.$refs.basicsForm.changeRulesValue([{ index: 3, key: "hidden", value: false }]);
			  } else {
				this.$refs.basicsForm.changeRulesValue([{ index: 3, key: "hidden", value: true }]);
			  }
			}
        return;
      }
	  if(data.key=='idCard'){
		  try{
		    let birthday = data.value.substring(6, 10) + "-" + data.value.substring(10, 12) + "-" + data.value.substring(12, 14)
		    if(this.isValidDate(new Date(birthday))){
				this.$refs.basicsForm.changeParamValue({
				  key: "birthday",
				  value: birthday
				});
				this.$refs.basicsForm.changeParamValue({
				  key: "age",
				  value: this.$util.getAgeBirth(birthday)
				});
				this.$refs.basicsForm.changeParamValue({
				  key: "sex",
				  value: 1 - (parseInt(data.value.substr(16, 1)) % 2 === 1?1:0),
				});
			}
		  }catch(e){
		    //TODO handle the exception
		  }
	  	return;
	  }
      if (data.key == "birthday") {
        this.$refs.basicsForm.changeParamValue({ key: "age", value: this.$util.getAgeBirth(data.value) });
        return;
      }
      if (data.key == "height") {
        this.height = data.value;
      } else if (data.key == "weight") {
        this.weight = data.value;
      }
      let bmi = "";
      if (this.height && this.weight) {
        bmi = Number((Number(this.weight) / Number(this.height) / Number(this.height)) * 10000).toFixed(2);
      }
      this.$refs.basicsForm.changeParamValue({ key: "bmi", value: bmi });
    },
	isValidDate(date) {
	  return date instanceof Date && !isNaN(date.getTime())
	},
    //获取验证码
    getCode() {
		setTimeout(()=>{
			if (this.codeWaitTime == 60) {
			  let rules = [
			    {
			      name: "telphone",
			      rule: ["required", "isMobile"],
			      msg: ["请输入手机号", "请输入正确的手机号"],
			    },
			  ];
			  let checkRes = form.validation({ telphone: this.telphone }, rules);
			  if (!checkRes) {
			    this.$api
			      .doctorSendSmsCodet({
			        phone: this.telphone,
			      })
			      .then((res) => {
			        if (res.code == 200) {
			          this.$util.showToast("验证码已发送，请注意查收");
			          this.codeWaitTime--;
			          this.timer = setInterval(() => {
			            this.codeWaitTime--;
			            if (!this.codeWaitTime) {
			              this.codeWaitTime = 60;
			              clearInterval(this.timer);
			            }
			          }, 1000);
			        }
			      });
			  } else {
			    this.$util.showToast(checkRes);
			  }
			}
		},100)
      
    },
    tapButton(index) {
      if (index) {
        this.$refs.basicsForm.formValid();
      } else {
        this.telphone = "";
        this.$refs.basicsForm.formReset();
      }
    },
    submit(param) {
      if (!param) {
        return;
      }
      uni.showModal({
        title: "提示",
        content: "确认保存？",
        success: (res1) => {
          if (res1.confirm) {
            let param2 = {};
            for (let key in param) {
              if (param[key] !== null && param[key] !== "" && param[key] !== undefined) {
                param2[key] = param[key];
              }
            }
            param2.provinceName = param2.pca[0];
            param2.cityName = param2.pca[1];
            param2.areaName = param2.pca[2];
            param2.diseaseCategory = this.diseaseList[param2.diseaseCategory];
            param2.nation = this.nationList[param2.nation];
            delete param2.pca;
            if (this.patientData && this.patientData.telphone == param2.telphone) {
              delete param2.smsCode;
            }
			if(!this.addFlag){
				param2.patientId=this.patientId
			}
            this.$api[this.addFlag?'doctorAddPatient':'patientUpdatePatient'](param2).then((res) => {
              if (res.code == 200) {
                uni.setStorageSync("refreshMyPatient", true);
				if(this.addFlag){
					uni.showModal({
					  title: "提示",
					  content: "保存成功，是否前往绑定设备？",
					  success: (res2) => {
					    if (res2.confirm) {
					      uni.redirectTo({
					        url: "/pagesPatient/equipmentList/index?patientId=" + res.data.patientId,
					      });
					    } else if (res2.cancel) {
					      this.$util.goUrl(0);
					    }
					  },
					});
				}else{
					this.$util.showSuccessToast('保存成功',true)
				}
              }
            });
          }
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
scroll-view {
  background: $back-grey-color;
  height: 100vh;
}
</style>
